package com.oscar.ehome.view.pageview;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.webkit.DownloadListener;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.joanzapata.pdfview.listener.OnDrawListener;
import com.joanzapata.pdfview.listener.OnLoadCompleteListener;
import com.joanzapata.pdfview.listener.OnPageChangeListener;
import com.oscar.ehome.R;
import com.oscar.ehome.base.C;
import com.oscar.ehome.base.activity.BasesPdf;
import com.oscar.ehome.presenter.BasePresenter;
import com.oscar.ehome.utils.system.SystemConfigFactory;
import com.oscar.ehome.utils.util.CommonUtils;
import com.oscar.ehome.utils.util.SystemBarTintManager;
import com.oscar.ehome.utils.util.ToastUtil;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by juxing
 * author: SunHaoZhao
 * date: On 2018/2/2
 */

public class ExcelWebActivity extends BasesPdf {

    SystemBarTintManager tintManager = null;
    String url = "";
    String fileName = "", open = "";//文件名
    int pageNumber = 1;
    int hengshu = 1;
    @BindView(R.id.title_img_back)
    ImageView titleImgBack;
    @BindView(R.id.title_tv_menu)
    TextView titleTvMenu;
    @BindView(R.id.title_layout_left)
    RelativeLayout titleLayoutLeft;
    @BindView(R.id.title_topbar)
    TextView titleTopbar;
    @BindView(R.id.img_spinner)
    ImageView imgSpinner;
    @BindView(R.id.liear_title)
    LinearLayout liearTitle;
    @BindView(R.id.title_tv_right)
    TextView titleTvRight;
    @BindView(R.id.title_img_right)
    ImageView titleImgRight;
    @BindView(R.id.title_img_right_new)
    ImageView titleImgRightNew;
    @BindView(R.id.title_img_right_dudao)
    ImageView titleImgRightDudao;
    @BindView(R.id.home_tv_num)
    TextView homeTvNum;
    @BindView(R.id.title_right_layput)
    RelativeLayout titleRightLayput;
    @BindView(R.id.basetitle_bar)
    RelativeLayout basetitleBar;
    @BindView(R.id.staticstics_webview)
    WebView staticsticsWebview;
    @BindView(R.id.quesiton_tj)
    Button quesitonTj;
    @BindView(R.id.taticstics_progressbar)
    ProgressBar taticsticsProgressbar;
String type;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_bannerweb);
        setBaseBackground(ExcelWebActivity.this);
        ButterKnife.bind(this);
        setColor();
        url = getIntent().getStringExtra("url");
        type= getIntent().getStringExtra("type");
        Log.e("456sss", "onItemClick: " + url);
        open = getIntent().getStringExtra("open");
        fileName = getIntent().getStringExtra("fileName");
        basetitleBar.setVisibility(View.VISIBLE);

        if (type.equals("1")) {//本地阅读
            initView();
        } else {//在线阅读

            titleImgBack.setImageResource(R.mipmap.fanhui);
            titleImgBack.setVisibility(View.VISIBLE);
            titleTopbar.setText("Excel");
            showLoading();
        }
addView();
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    /**
     * 设置颜色
     */
    public void setColor() {

        basetitleBar.setBackgroundColor(Color.parseColor(SystemConfigFactory.getInstance(ExcelWebActivity.this).getSystemConfig().getColor()));
//        TintManager.setTint(roundProgressBar, Color.parseColor(SystemConfigFactory.getInstance(this).getSystemConfig().getColor()));
    }


    String fileAbsolutePath;

    /**
     * 打开本地PDF
     */
    public void initView() {
        titleImgBack.setImageResource(R.mipmap.fanhui);
        titleImgBack.setVisibility(View.VISIBLE);
        titleTopbar.setText("Excel");
        if (open != null && open.equals("ture")) {
            fileAbsolutePath = CommonUtils.getSDCardRootPath() + C.video + fileName;

            titleTvRight.setVisibility(View.VISIBLE);
            titleTvRight.setText("发送");
            titleImgBack.setVisibility(View.VISIBLE);
            titleImgBack.setImageResource(R.mipmap.fanhui);
        } else {
            fileAbsolutePath = CommonUtils.getSDCardRootPath(ExcelWebActivity.this) + C.video + fileName;

            titleTvRight.setVisibility(View.GONE);
            titleImgBack.setVisibility(View.VISIBLE);
            titleImgBack.setImageResource(R.mipmap.fanhui);
        }

    }

    /**
     * 展示网页
     */
    public void addView() {

        staticsticsWebview.setWebViewClient(new WebViewClient() {
            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//              super.onReceivedSslError(view, handler, error);
                handler.proceed();
//              handleMessage(Message msg); 其他处理
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return false;
                }
                try {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                }
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
            }
        });
        staticsticsWebview.setDownloadListener(new MyDownloadStart());
        // WebView加载web资源


        WebSettings webSettings = staticsticsWebview.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings
                .setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);// 排版适应屏幕
        webSettings.setLoadWithOverviewMode(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP)
            webSettings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);


        webSettings.setDomStorageEnabled(true);


        webSettings.setDefaultTextEncodingName("utf-8");
        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setSavePassword(false);
        webSettings.setSaveFormData(true);// 保存表单数据

        webSettings.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);

        //关闭webview中缓存
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片


        // setUseWideViewPort方法设置webview推荐使用的窗口。setLoadWithOverviewMode方法是设置webview加载的页面的模式ist.get(position);
        staticsticsWebview.setInitialScale(100);
        staticsticsWebview.setHorizontalScrollBarEnabled(false);// 水平不显示
        staticsticsWebview.setVerticalScrollBarEnabled(false); // 垂直不显示
        staticsticsWebview.setScrollBarStyle(View.SCROLLBARS_OUTSIDE_OVERLAY);
        staticsticsWebview.loadUrl("https://view.officeapps.live.com/op/view.aspx?src="+url);
        staticsticsWebview.setWebChromeClient(new WebChromeClient() {

            public void onProgressChanged(WebView view, int progress) {
                taticsticsProgressbar.setProgress(progress * 100);
                if (progress == 100) {
                    dismissLoading();
                }
            }
        });
    }


    class MyDownloadStart implements DownloadListener {

        @Override
        public void onDownloadStart(String url, String userAgent,
                                    String contentDisposition, String mimetype, long contentLength) {
            // TODO Auto-generated method stub
            //调用自己的下载方式
            // new HttpThread(url).start();
            //调用系统浏览器下载
            Uri uri = Uri.parse(url);
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }

    @OnClick({R.id.title_layout_left, R.id.quesiton_tj, R.id.title_tv_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_tv_right:
                if (titleTvRight.getText().equals("发送")) {

                    if (GetVideoFileName(fileAbsolutePath)) {
                        new PopupWindows(ExcelWebActivity.this, titleTvRight);
                    } else {
                        ToastUtil.show(ExcelWebActivity.this, "未查找到该文件。");
                    }
                } else {
                }

                break;

            case R.id.title_layout_left:

                finish();


                break;
        }
    }

    /**
     * 查询内存卡是否下载该文件
     *
     * @param fileAbsolutePath
     * @return
     */
    public boolean GetVideoFileName(String fileAbsolutePath) {
        File dstDiretory = new File(fileAbsolutePath);
        if (dstDiretory.exists()) {// 目标目录不存在
            return true;
        }
        return false;
    }


    public void setBaseBackground(Activity act) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            CommonUtils.setTranslucentStatus(true, act);
            tintManager = new SystemBarTintManager(act);
            tintManager.setStatusBarTintEnabled(true);
            tintManager.setStatusBarTintColor(Color.parseColor(SystemConfigFactory.getInstance(ExcelWebActivity.this).getSystemConfig().getColor()));
        }
    }

    public class PopupWindows extends PopupWindow {

        public PopupWindows(Context mContext, View parent) {

            View view = View.inflate(mContext, R.layout.fenxiangbuju, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view
                    .findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.push_bottom_in_2));

            setWidth(ViewGroup.LayoutParams.MATCH_PARENT);
            setHeight(ViewGroup.LayoutParams.MATCH_PARENT);
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);
            update();
            Button bt1 = (Button) view
                    .findViewById(R.id.item_popupwindows_Photo);
            Button bt2 = (Button) view
                    .findViewById(R.id.item_popupwindows_qq);
            Button bt3 = (Button) view
                    .findViewById(R.id.item_popupwindows_center);
            bt1.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);
                    File f = new File(fileAbsolutePath);
                    sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
                    sendIntent.setType("*/*");
                    sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");//微信朋友
//          sendIntent.setClassName("com.tencent.mobileqq", "cooperation.qqfav.widget.QfavJumpActivity");//保存到QQ收藏
//          sendIntent.setClassName("com.tencent.mobileqq", "cooperation.qlink.QlinkShareJumpActivity");//QQ面对面快传
//          sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.qfileJumpActivity");//传给我的电脑
                    //sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");//QQ好友或QQ群
//          sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");//微信朋友圈，仅支持分享图片
                    startActivity(sendIntent);


                    dismiss();

                }
            });
            bt2.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {

                    Intent sendIntent = new Intent();
                    sendIntent.setAction(Intent.ACTION_SEND);

                    File f = new File(fileAbsolutePath);
                    sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
                    sendIntent.setType("*/*");
                    // sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareImgUI");//微信朋友
//          sendIntent.setClassName("com.tencent.mobileqq", "cooperation.qqfav.widget.QfavJumpActivity");//保存到QQ收藏
//          sendIntent.setClassName("com.tencent.mobileqq", "cooperation.qlink.QlinkShareJumpActivity");//QQ面对面快传
//          sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.qfileJumpActivity");//传给我的电脑
                    sendIntent.setClassName("com.tencent.mobileqq", "com.tencent.mobileqq.activity.JumpActivity");//QQ好友或QQ群
//          sendIntent.setClassName("com.tencent.mm", "com.tencent.mm.ui.tools.ShareToTimeLineUI");//微信朋友圈，仅支持分享图片
                    startActivity(sendIntent);


                    dismiss();

                }
            });
            bt3.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }
}
